const express = require('express');
const router = express.Router();

// 导入工具和中间件
const { success, error, badRequest, unauthorized, asyncHandler } = require('../utils/response');
const { authenticateToken } = require('../utils/auth');

// 导入服务层
const authService = require('../services/authService');

/**
 * 用户登录
 * POST /auth/login
 */
router.post('/login', asyncHandler(async (req, res) => {
  try {
    const result = await authService.loginUser(req.body);
    success(res, result);
  } catch (err) {
    if (err.message.includes('用户名或密码错误') || err.message.includes('账号已被禁用')) {
      return unauthorized(res, err.message);
    }
    return badRequest(res, err.message);
  }
}));

/**
 * 用户注册
 * POST /auth/register
 */
router.post('/register', asyncHandler(async (req, res) => {
  try {
    const result = await authService.registerUser(req.body);
    success(res, result);
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

/**
 * 获取用户信息
 * GET /auth/profile
 */
router.get('/profile', authenticateToken, asyncHandler(async (req, res) => {
  try {
    const result = await authService.getUserProfile(req.user.id);
    success(res, result);
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

/**
 * 更新用户信息
 * PUT /auth/profile
 */
router.put('/profile', authenticateToken, asyncHandler(async (req, res) => {
  try {
    const result = await authService.updateUserProfile(req.user.id, req.body);
    success(res, result, '更新成功');
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

/**
 * 刷新令牌
 * POST /auth/refresh
 */
router.post('/refresh', asyncHandler(async (req, res) => {
  try {
    const result = await authService.refreshTokenService(req.body.refreshToken);
    success(res, result);
  } catch (err) {
    return unauthorized(res, err.message);
  }
}));

/**
 * 修改密码
 * PUT /auth/password
 */
router.put('/password', authenticateToken, asyncHandler(async (req, res) => {
  try {
    await authService.changePassword(req.user.id, req.body);
    success(res, null, '密码修改成功');
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

/**
 * 用户登出
 * POST /auth/logout
 */
router.post('/logout', authenticateToken, asyncHandler(async (req, res) => {
  // 在实际项目中，可以将token加入黑名单
  // 这里简单返回成功
  success(res, null, '登出成功');
}));

module.exports = router;
